<!-- src/views/product/add.vue -->
<template>
	<div class="product-add">
		<div class="header">
			<el-button type="default" @click="$router.go(-1)">返回</el-button>
		</div>
		<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
			<el-form-item label="商品图片">
				<el-upload v-model:file-list="fileList"
					action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" list-type="picture-card"
					:auto-upload="false">
					<el-icon>
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>

			<el-form-item label="商品编码" prop="itemCode">
				<el-input v-model="form.itemCode" />
			</el-form-item>

			<el-form-item label="商品名称" prop="name">
				<el-input v-model="form.name" />
			</el-form-item>

			<el-form-item label="类别" prop="category">
				<el-select v-model="form.category" placeholder="请选择类别">
					<el-option v-for="category in categories" :key="category.value" :label="category.label"
						:value="category.value" />
				</el-select>
			</el-form-item>

			<el-form-item label="价格" prop="price">
				<el-input v-model.number="form.price" type="number" />
			</el-form-item>

			<el-form-item label="数量" prop="quantity">
				<el-input v-model.number="form.quantity" type="number" />
			</el-form-item>

			<el-form-item label="单位" prop="unit">
				<el-select v-model="form.unit" placeholder="请选择单位">
					<el-option v-for="unit in units" :key="unit" :label="unit" :value="unit" />
				</el-select>
			</el-form-item>

			<!-- <el-form-item label="最小数量" prop="minQuantity">
				<el-input v-model="form.minQuantity" type="number" />
			</el-form-item>

			<el-form-item label="最大数量" prop="maxQuantity">
				<el-input v-model="form.maxQuantity" type="number" />
			</el-form-item> -->

			<!-- <el-form-item label="状态" prop="status">
				<el-switch v-model="form.status" />
			</el-form-item> -->

			<el-form-item label="备注" prop="remark">
				<el-input v-model="form.remark" type="textarea" />
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import api from '@/request/index'
import cigarettes from '@/utils/cigarettes'

onMounted(() => {
	if (route.query.itemCode) {
		form.value.itemCode = route.query.itemCode
	}
})

const route = useRoute()

const formRef = ref(null)
const loading = ref(false)
const form = ref({
	image: '',
	itemCode: '',
	name: new Date().getTime().toString(),
	category: '其他',
	unit: '个',
	quantity: 99999,
	// minQuantity: '',
	// maxQuantity: '',
	price: '',
	status: true,
	remark: ''
})

const rules = {
	itemCode: [{ required: true, message: '商品编码是必填项', trigger: 'blur' }],
	name: [{ required: true, message: '商品名称是必填项', trigger: 'blur' }],
	category: [{ required: true, message: '类别是必填项', trigger: 'blur' }],
	unit: [{ required: true, message: '单位是必填项', trigger: 'blur' }],
	quantity: [
		{ required: true, message: '数量是必填项', trigger: 'blur' },
		{ type: 'number', message: '数量必须是数字', trigger: 'blur' }
	],
	price: [
		{ required: true, message: '价格是必填项', trigger: 'blur' },
		{ type: 'number', message: '价格必须是数字', trigger: 'blur' }
	]
}

const categories = ref(cigarettes.map(item => ({ value: item, label: item })))
const units = ref(['包', '条', '盒', '箱', '件', '瓶', '罐', '袋', '桶', '盒', '个'])
const fileList = ref([])

const submitForm = async () => {
	console.log('提交的表单数据:', form.value)
	try {
		await formRef.value.validate()
		// 表单验证通过，可以进行提交操作
		ElMessage.success('表单验证通过，正在提交...')
		submit()
		// 这里可以添加提交表单的逻辑，例如调用API
	} catch (error) {
		console.log(error)
		ElMessage.error('表单验证失败，请检查输入')
	}
	// 这里可以添加提交表单的逻辑
}

const uploadImage = async () => {
	let promiseArr = []
	fileList.value.map(async file => {
		promiseArr.push(
			new Promise(resolve => {
				if (file.status !== 'success') {
					const formData = new FormData()
					formData.append('file', file.raw)
					api
						.uploadImage(formData)
						.then(res => {
							file.status = 'success'
							resolve(res.data.url)
						})
						.catch(() => {
							file.status = 'error'
							resolve(null)
						})
				} else {
					resolve(file.url)
				}
			})
		)
	})
	return Promise.all(promiseArr)
}

const submit = async () => {
	loading.value = true
	let urls = await uploadImage()
	try {
		let params = JSON.parse(JSON.stringify(form.value))
		params.image = urls.join(';')
		await api.productAdd(params)
		ElMessage.success('商品添加成功')
		resetForm()
	} catch (error) {
		ElMessage.error('商品添加失败')
	} finally {
		loading.value = false
	}
}

const resetForm = () => {
	form.value = {
		image: '',
		itemCode: '',
		name: new Date().getTime().toString(),
		category: '其他',
		unit: '个',
		quantity: 99999,
		price: '',
		remark: ''
	}
	fileList.value = []
}
</script>

<style scoped lang="less">
.product-add {
	border-radius: 10px;
	background-color: #fff;
	padding: 20px;
	margin: 20px;

	.header {
		margin-bottom: 20px;
	}
}

.upload-demo {
	margin-bottom: 20px;
	/* 调整上传区域与表单的间距 */
}
</style>
